<?php
namespace Popshouse\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\SecurityContext;

use Popshouse\AdminBundle\Helper\Image;
use Popshouse\AdminBundle\Form\PageForm;

use Popshouse\AdminBundle\Helper\Arr;

class PageController extends Controller {
	
	/**
	 * @extra:Template()
	 */
	public function indexAction() {
		$em = $this->get ( 'doctrine.orm.entity_manager' );
		
		$query = $em->createQuery ( "SELECT p FROM Popshouse\SiteBundle\Entity\Page p ORDER BY p.id ASC" );
		$pages = $query->getResult ();
		return array ('pages' => $pages, 'active' => 'page' );
	}
	
	/**
	 * @extra:Template()
	 */
	public function editAction($id = 0) {
		$em = $this->get ( 'doctrine.orm.entity_manager' );
		
		$page = $em->find ( 'Popshouse\SiteBundle\Entity\Page', $id );
		if ($page === null || ! $page->getId ())
			throw new \Exception ( "Deze pagina werd niet gevonden" );
	//	die($page->getImgPosition()."".$page->getImgWidth());
		$form = $this->get ( 'form.factory' )->createNamed ( new PageForm(), 'page', $page );
		$request = $this->get ( 'request' );
		
		if ($request->getMethod () == 'POST') {
			$form->bindRequest ( $request );
			if ($form->isValid ()) {
				
				$order = $this->get('request')->request->get('order');
			
				if(!empty($order)){
					$orders = Arr::decodeJSArray($order);
					$query = $em->createQuery("SELECT i FROM Popshouse\SiteBundle\Entity\Pageimg i WHERE i.id IN (". implode(',',$orders) .")");
					$images = $query->getResult();
					
					
					foreach($orders as $index => $order){
						$page->addImgSide($em,$images[$index],$index);
					}
				
					
				}
		
				$em->flush();
			    $this->get('session')->setFlash('notice', 'Pagina instellingen opgeslaan!');
	            return new RedirectResponse($this->generateUrl('page'));
	        
			}
		}
		
		$query = $em->createQuery("SELECT i FROM Popshouse\SiteBundle\Entity\Pageimg i WHERE :pageId NOT MEMBER OF i.onPages ORDER BY i.id ASC");
		$query->setParameter('pageId', $page->getId());
	
		$images = $query->getResult ();
		
		return array ('form' => $form->createView (), 'page' => $page, 'images' => $images, 'active' => 'page' );
	}

}
